<template>
  <div class="container">
    <el-row :gutter="10" type="flex" justify="start" class="mb14">
      <el-col :span="1.5" class="text-align-left">
        <div id="messBox">下列服务编码还未返回预估单：{{ coding }}</div>
        <div class="color-red">
          预估单未返回时请确认以下操作是否已完成：
        </div>
        <div
          v-for="(item, index) in textArray"
          :key="index"
          class="color-red"
        >
          {{ item }}
        </div>
      </el-col>
    </el-row>
    <wz-table  :columns="columns" :use-index="true" :table-data="tableData" :getListMethod="getListMethod">
      <!-- 单价 -->
      <template #price="{ row }">
        <div v-if="row.serviceCode">
          {{ roundingFour(row.price) }}
        </div>
      </template>
      <template #projectProgress="{ row }">
        <div v-if="!row.serviceCode">
          <el-input
            v-if="row.isOk3 && !row.strVid && editor == 'true'"
            v-model="row.projectProgress"
            @blur="handleBlur(row, 'projectProgress')"
          />
          <div v-else @click="handleEdit(row)">
            {{ row.projectProGress }}
          </div>
        </div>
      </template>
      <!--  商合预占金额(元)-->
      <template #shMoney="{ row }">
        <div v-if="row.serviceCode">
          {{ rounding(row.shMoney) }}
        </div>
      </template>
      <!-- 累计验工计价数量 -->
      <template #sumNum="{ row }">
        <div v-if="row.serviceCode">
          {{ roundingFour(row.sumNum) }}
        </div>
      </template>
      <!-- 累计验工金额(元) -->
      <template #sumMoney="{ row }">
        <div v-if="row.serviceCode">
          {{ rounding(row.sumMoney) }}
        </div>
      </template>
      <!-- 本期验工数量 -->
      <template #currentInspectionNum="{ row }">
        <div v-if="!row.serviceCode">
          <el-input
            v-if="row.paymentType!=='FIRST'&&isCurrentInspectionNumInput(row)&&flageColor.currentInspectionNumColor"
            ref="currentInspectionNum"
            v-model="row.currentInspectionNum"
            size="mini"
            type="text"
            placeholder=""
            @blur="handleBlur(row)"
          />
          <div
            :style="{'background':isCurrentInspectionNumInput(row)&&row.paymentType!=='FIRST'?'#fffaee':''}"
            v-else
            @click="isCurrentInspectionNumInput(row)&&row.paymentType!=='FIRST'?handleEdit(row, 'currentInspectionNum'):''"
          >
            {{ roundingFour(row.currentInspectionNum) }}
          </div>
        </div>
      </template>
      <template #orderState="{ row }">
        <div>
          {{ orderStateDictionaries(row) }}
        </div>
      </template>
      <template #currentDeductionMoney="{ row }">
        <div v-if="!row.serviceCode">
          <el-input
            v-if="isCurrentDeductionMoney(row)&&flageColor.currentDeductionMoneyColor"
            ref="currentDeductionMoney"
            v-model="row.currentDeductionMoney"
            size="mini"
            type="text"
            placeholder=""
            @blur="handleBlur(row)"
          />
          <div
          :style="{'background':isCurrentDeductionMoney(row)?'#fffaee':''}"
            v-else
            @click="isCurrentDeductionMoney(row)?handleEdit(row, 'currentDeductionMoney'):''"
          >
            {{ roundingFour(row.currentDeductionMoney) }}
          </div>
        </div>
      </template>
      <template #subChildrenCode="{ row }">
       <div v-if="!row.serviceCode">
            <span @click="selectContract(row)" :class="['header-tooltip']" :style="{'color':row.subNicheCode?'#22a3ff':'#ccc'}">{{row.subNicheCode?row.subNicheCode:'请选择'}}</span>
       </div>
      </template>
      <!-- 起始时间 -->
        <template #shareStartDate="{ row }">
            <div v-if="!row.serviceCode">
            <el-date-picker
                :disabled="newShowField(row)"
                @change="newHandlerBlur(row)"
                v-model="row.shareStartDate"
                :value-format="'yyyy-MM-dd'"
                :format="'yyyy-MM-dd'"
                type="date"
                placeholder="选择日期"
                :picker-options="startDateOptions(row)"
                >
            </el-date-picker>
            </div>
        </template>
        <!-- 结束时间 -->
        <template #shareEndDate="{ row }">
            <div v-if="!row.serviceCode">
            <el-date-picker
                :disabled="newShowField(row)"
                @change="newHandlerBlur(row)"
                v-model="row.shareEndDate"
                :value-format="'yyyy-MM-dd'"
                :format="'yyyy-MM-dd'"
                type="date"
                :picker-options="endDateOptions(row)"
                placeholder="选择日期">
            </el-date-picker>
            </div>
        </template>
      <!-- 项目进度 -->
      <template #projectProGress="{ row }">
        <div>
          <div v-if="!row.serviceCode">
            <el-input
              v-if="row.paymentType!=='FIRST'&&isProgress(row)&&flageColor.projectProGressColor"
              ref="projectProGress"
              v-model="row.projectProGress"
              size="mini"
              type="text"
              placeholder=""
              @blur="handleBlur(row)"
            />
            <div :style="{'background':isProgress(row)&&row.paymentType!=='FIRST'?'#fffaee':''}" v-else @click="isProgress(row)&&row.paymentType!=='FIRST'?handleEdit(row, 'projectProGress'):''">
              {{ row.projectProGress }}
            </div>
          </div>
        </div>
      </template>
      <template #isPush="{ row }">
        <div>
          {{ isPushDictionaries(row) }}
        </div>
      </template>
      <template #paymentType="{ row }">
        <div>
          {{ payType(row) }}
        </div>
      </template>
      <!-- 1:新增，2：冲销，3：查看 -->
      <template #operation="{ row }">
        <div>
          <el-button
            v-if="isAdd(row)"
            class="pms-button-primary-plain"
            @click="add(row)"
          >新增</el-button>
          <el-button
            v-if="isTrade(row)"
            class="pms-button-primary-plain"
            @click="trade(row)"
          >冲销</el-button>
          <el-button
            v-if="(newZlCalc&&isNewDeleteZl(row))?+row.ifDelFirstZL===1:isDelete(row)"
            class="pms-button-primary-plain"
            @click="handleDelete(row)"
          >删除</el-button>
        </div>
      </template>
    </wz-table>
    <el-dialog class="pms-zr-dialog" ref="contractCode" :close-on-click-modal="false" :visible.sync="showContractCode"
    title="选择子商机编码" width="60%">
    <div style="display: flex;justify-content: space-between;">
      <div style="color:red">建设单位:{{cityName}}</div>
    </div>
    <el-table :data="contractTableData" style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
      <el-table-column align="center" type="index" label="序号" width="50"  />
      <el-table-column prop="industryCode" label="跨行业业务编码" width="180" align="center" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="subNicheCode" label="子商机编码" align="center" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="subNicheName" label="子商机名称" align="center" show-overflow-tooltip>
    </el-table-column>
    <!-- <el-table-column prop="count" label="工作量" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
            <div>
            <span style="color: red;">*</span>
            <el-input  type="number" class="pms-wz-input el-table-inline" v-model="scope.row.workAmount" size="mini" />
        </div>
        </template>
      </el-table-column> -->
    <el-table-column prop="count" label="金额" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
            <div>
                <span style="color: red;">*</span>
          <el-input required type="number" class="pms-wz-input el-table-inline" v-model="scope.row.money" size="mini">
          </el-input>
        </div>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button class="pms-button-primary" @click="confirmSave">确 定</el-button>
      <el-button class="pms-button-primary" @click="showContractCode = false">取 消</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
import { INSPECTION_VALUATION_TEXT, CHECK_DELETE_TIPS } from '../enum/textEnum'
import { INSPECTION_VALUATION_DETAILS } from '../enum/table'
import {
    queryInsValDetailsTao,
    getServiceReceInspection,
    getHaveInspection,
    getItAccInfo,
    checkIfValidatePrecision,
    getMaterialInfo,
    getCheckInsVaData,
    updateInsValITNew,
    getSubCode,
    saveSubCode,
    isShowSubCode,
    getPrjDetail,
    saveTime
} from '@/api/checkoutValuation/index'
// import {
//     checkIfValidatePrecision,
//     getMaterialInfo,
//     getCheckInsVaData,
//     updateInsValITNew,
// } from '@/api/checkoutValuation'
import checkOutEnum from '@/mixins/checkOutEnum'
import checkoutValuation from '@/mixins/checkoutValuation'
export default {
    name: 'InspectionValuationDetails',
    mixins: [checkOutEnum, checkoutValuation],
    props: {
        prjId: {
            type: [String, Number],
            default: ''
        },
        nodeNameWord: {
            type: String,
            default: ''
        },
        itAccId: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            coding: [],
            textArray: [],
            columns: [],
            tableData: [],
            options: [],
            fatherNodeArr: [],
            sign: false,
            nodeName: '',
            oldCspectionNum: '',
            oldCspectionMoney: '',
            oldRow: {},
            oldParentRow: {},
            currentRow: {},
            currentParentRow: {},
            isValid: false,
            isTardeOrAdd: 1,
            flageColor:{
                projectProGressColor:false,
                currentInspectionNumColor:false,
                currentDeductionMoneyColor:false,
            },
            showContractCode:false,
            contractTableData:[],
            multipleContractSelection: [],
            saveSubCodeObj:{},
            cityName:'',
            prjDetail:{},
        }
    },
    computed: {
        // 智联服务成本展示时间
         newZlSoftWort(){
            return this.prjDetail.isNewbusiness==='1'&&['25'].includes(this.prjDetail.buildModes)&&this.prjDetail.prjType==='W'
        },
        newZlCalc(){
            return this.prjDetail.isNewbusiness==='1'&&['25','29'].includes(this.prjDetail.buildModes)
        },
        query() {
            console.log(this.$route.query)
            return this.$route.query
        },
        isAdd() {
            return (row) => {
                return (
                     this.optimizeNewOne(row) || this.optimizeNewTwo(row)
                )
            }
        },
        // 2024-10-09 阻断问题if过多解决方案
        optimizeNewFive() {
            return (+this.query.queryType === 2 ||
                        (this.nodeNameWord === 'alliv01new' &&
                            this.isTardeOrAdd === 2))
        },
        isTrade() {
            return (row) => {
                const fartherNode = this.getParentNode(row)
                const parentNode = +Math.abs(Number(fartherNode?.sumMoney || 0))
                console.log(!!+parentNode, parentNode)
                const flag = Math.sign(row.currentInspectionMoney)
                // !this.getIsAllTrade(fartherNode)
                return (
                    this.optimizeNewFive && this.optimizeNewSix(row, parentNode, flag, fartherNode)
                )
            }
        },
        isNewDeleteZl(){
            return (row) => {
                return (
                    this.isDelete(row)&&row.orderState==='1'&&(+row.currentInspectionMoney)>0&&row.paymentType==="FIRST"
                )
            }
        },
        isDelete() {
            return (row) => {
                return (
                    +row.isPush === 0 &&
                    this.getParentNodeOrderState(row) === '1'
                )
            }
        },
        optimizeNewSeven() {
            const _arr = ['acceptance_v103','shishi_zlgmfw01', 'shishi_tzrj01', 'shishi_gz01','alliv01new']
            return _arr.includes(this.nodeNameWord)
        },
        optimizeNewNine() {
            return (+this.query.queryType === 1 || +this.query.queryType === 2 || this.query.type === 'todo')
        },
        isCurrentInspectionNumInput() {
            return (row) => {
                return (this.optimizeNewEight(row) && this.optimizeNewSeven)||this.isCurrentInspectionNumInputOne(row)
            }
        },
        isCurrentInspectionNumInputOne(){
            return (row) => {
                return this.optimizeNewEightInfo(row) && this.optimizeNewSeven&&this.isCurrentInspectionNumInputTwo(row)
            }
        }, 
        isCurrentInspectionNumInputTwo(){
            return (row) => {
                return this.isshowPrjDetailInfo&&row.spcalTag
            }
        },
        isshowPrjDetailInfo(){
            return this.prjDetail.isNewbusiness==='1'&&['25','29'].includes(this.prjDetail.buildModes)
        },
        isCurrentDeductionMoney() {
            return (row) => {
                return (
                    this.optimizeNewTen(row) &&
                     this.optimizeNewNine && this.optimizeNewEleve(row)
                )
            }
        },
        isProgress() {
            return (row) => {
                return row.isProgressEdit && !row.strVid && +row.isPush === 0 &&['acceptance_v103','shishi_zlgmfw01','shishi_tzrj01','alliv01new','shishi_gz01'].includes(this.nodeNameWord)
            }
        },
        isEdit() {
            // 这个判断是判断来自哪个页面
            if (+this.query.queryType === 1 || +this.query.queryType === 2) {
                return true
            } else {
                if (this.nodeNameWord === 'alliv01new') {
                    return true
                }
                if (this.nodeNameWord === 'alliv02new') {
                    return true
                }
                return false
            }
        }
    },
    watch: {
        tableData(val) {
            this.initCellColor()
        },
        async prjId(val) {
            if (val) {
                await this.getInitPriDetail()
                this.queryInspectionValuationDetailsAll({
                    prjId: this.query.prjId || this.prjId
                })
                this.getServiceReceInspection({
                    prjId: this.query.prjId || this.prjId
                })
                const res = await getItAccInfo({
                    prjId: this.query.prjId || this.prjId
                })
                if (+res.code === 200) {
                    this.isTardeOrAdd =
                        res.data.find((item) => item.itAccId === this.itAccId)
                            ?.type === '新增'
                            ? 1
                            : 2
                }
                this.initCellColor()
            }
        },
        nodeNameWord(value) {
            if (value !== 'alliv01new' && +this.query.queryType === 3) {
                this.columns.pop()
            } else if (
                value === 'alliv01new' ||
                +this.query.queryType === 1 ||
                +this.query.queryType === 2
            ) {
                this.columns = JSON.parse(
                    JSON.stringify(INSPECTION_VALUATION_DETAILS)
                )
            } else {
                this.columns.pop()
            }
        },
        isTradeOrAdd(val) {
            console.log(val)
        }
    },
   async mounted() {
        this.cityName = JSON.parse(sessionStorage.getItem('SET_LOGINDATA'))?.workGroupName || ''
       this.textArray = INSPECTION_VALUATION_TEXT
       this.columns = JSON.parse(JSON.stringify(INSPECTION_VALUATION_DETAILS))
       if (+this.query.queryType === 3) {
           this.columns.pop()
       }
    },
    methods: {
        convertToYMD(dateString) {
            const date = new Date(dateString);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        startDateOptions(row) {
            return {
                disabledDate: (time) => {
                    if (row.shareEndDate) {
                        const endDate = new Date(row.shareEndDate);
                        return time.getTime() > endDate.getTime() && this.convertToYMD(time) !== row.shareEndDate;
                    }
                    return false;
                }
            };
        },
        endDateOptions(row) {
            return {
                disabledDate: (time) => {
                    if (row.shareStartDate) {
                        const startDate = new Date(row.shareStartDate);
                        return time.getTime() < startDate.getTime() && this.convertToYMD(time) !== row.shareStartDate;
                    }
                    return false;
                }
            };
        },
        // 是否能编辑时间
        newShowField(row) {
            if(this.nodeNameWord!=='alliv01new'){
                return true
            }
            if(['FIRST','PROGRESSING'].includes(row.paymentType)&&['0'].includes(row.isPush)&&(+row.currentInspectionMoney)>=0&&+row.isEditor===1){
                return false
            }
            return true
        },
        // 分摊开始时间结束时间保存数据
        async newHandlerBlur(row) {
            const params = {
                valuationDetailId: row.vid,
                shareStartDate: row.shareStartDate?row.shareStartDate:"",
                shareEndDate: row.shareEndDate?row.shareEndDate:""
            }
            // 保存行数据并刷新表格数据
            const {code} = await saveTime(params)
            if(+code===200){
                this.$message({
                    message: '保存成功',
                    type: 'success'
                })
                await this.getNewData()
            }
        },
      async confirmSave(){
        if(this.multipleContractSelection.length===0){
            this.$message.warning('请选择一条数据')
            return
        }
        const enums = ['',null]
        const notWrite = !this.multipleContractSelection.some(v=>enums.includes(v.money))
        if(!notWrite){ 
            this.$message.error('请填写金额')
            return 
        }
        const addParams = {
            valuationId:this.saveSubCodeObj?.pid,
            valuationDetailId:this.saveSubCodeObj?.vid,
            prjId:this.saveSubCodeObj?.prjId,
            subPrjId:this.saveSubCodeObj?.subPrjId,
        }
        const result = this.multipleContractSelection.map(item=>{
            return {
                ...addParams,
                ...item
            }
        })
        const finishParams = {
            subNicheVoList:result
        }
       const {code} = await saveSubCode(finishParams)
         if(+code===200){
            await this.getNewData()
            this.showContractCode = false
            this.$message.success('保存成功')
          }
      },   
        // 全选
        handleSelectionChange(list){
            this.multipleContractSelection = list
        },
       async selectContract(row){
            this.saveSubCodeObj = row 
            if(!(['FIRST','PROGRESSING'].includes(row.paymentType)&&['0'].includes(row.isPush)&&(+row.currentInspectionMoney)>0)){
                return
            }
            if(this.nodeNameWord!=='alliv01new'){
                return
            }
            this.showContractCode = true
            const {code,data} = await getSubCode({prjId:this.prjId,valuationDetailId:this.saveSubCodeObj?.vid})
            if(+code===200){
                this.contractTableData = data
            }
        },
        async getInitPriDetail() {
            const res = await getPrjDetail({prjId:this.prjId})
            this.prjDetail = res.data
            const {code,data} = await isShowSubCode({prjId:this.prjId})
            if (+code === 200&&(+data===0)) {
                this.columns = this.columns.filter(item => item.prop !== 'subChildrenCode')
            }
            // 智联服务成本展示时间字段
            if(!this.newZlSoftWort){
                const _arrType = ['shareStartDate','shareEndDate']
                this.columns = this.columns.filter(item => !_arrType.includes(item.prop))
            }
        },
         initCellColor() {
            const _types = ['projectProGress', 'currentInspectionNum', 'currentDeductionMoney']
            for (let i = 0; i < _types.length; i++) {
                this.tableData.forEach((row) => {
                    this.handleEdit(row, _types[i],false)
                })
            }
        },
        getListMethod(){
            console.log("");
        },
        // 2024-10-09 阻断问题if过多解决方案
        optimizeNewOne(row) {
            return (this.nodeNameWord === 'alliv01new' &&
                        this.isTardeOrAdd === 1 && this.optimizeNewThree(row))
        },
        // 2024-10-09 阻断问题if过多解决方案
        optimizeNewTwo(row) {
            return (+this.query.queryType === 1 && this.optimizeNewFour(row))
        },
        // 2024-10-09 阻断问题if过多解决方案
        optimizeNewThree(row) {
            return +row.pid === 0 &&
                        +row.orderState === 1 &&
                        +row.ifAdd === 1
        },
        // 2024-10-09 阻断问题if过多解决方案
        optimizeNewFour(row) {
            return +row.pid === 0 &&
                        +row.orderState === 1 &&
                        +row.ifAdd === 1
        },
        // 2024-10-09 阻断问题if过多解决方案
        optimizeNewSix(row, parentNode, flag, fartherNode) {
            return this.optimizeNewSixrepairOne(row) && !!+parentNode && flag === 1 && Number(fartherNode?.sumMoney) > 0
        },
        optimizeNewSixrepairOne(row){
            return row.paymentType === 'PROGRESSING' &&+row.isPush === 1
        },
        optimizeNewEight(row) {
            return row.edit && !row.strVid && +row.isPush === 0
        },
        optimizeNewEightInfo(row) {
            return row.edit && row.strVid && +row.isPush === 0
        },
        optimizeNewTen(row) {
            const one = ['alliv02new'] //信息化
            const two = ['acceptance_v103','shishi_zlgmfw01','alliv01new']
            const currentNode = this.prjDetail.prjType ==='M'?one:two
            return row.isCurrentDeductionMoney && currentNode.includes(this.nodeNameWord)
        },
        optimizeNewEleve(row) {
            return this.isTardeOrAdd === 1 && +row.isPush === 0&&row.paymentType==='PROGRESSING'
        },
        // 失去焦点数据准备
        handleBlur(row) {
            console.log(row)
            let fuDataVal = ''
            this.fatherNodeArr.map((fuVal) => {
                if (fuVal.vid === row.pid) {
                    fuDataVal = fuVal
                }
            })
            this.oldParentRow = JSON.parse(JSON.stringify(fuDataVal))
            row.currentInspectionNum = this.roundingFour(
                row.currentInspectionNum
            )
            // row.currentInspectionMoney = this.rounding(
            //     Number(row.currentInspectionNum) * Number(fuDataVal.price) -
            //         Math.abs(row.currentDeductionMoney)
            // )
               row.currentInspectionMoney = this.rounding(
                Number(row.currentInspectionNum) * Number(fuDataVal.price)
            )
            fuDataVal.sumNum = this.roundingFour(
                Number(fuDataVal.sumNum) -
                    Number(this.oldCspectionNum) +
                    Number(row.currentInspectionNum)
            )
            fuDataVal.sumMoney = this.rounding(
                Number(fuDataVal.sumMoney) -
                    Number(this.oldCspectionMoney) +
                    Number(row.currentInspectionMoney) - Math.abs(row.currentDeductionMoney) + Math.abs(this.oldRow.currentDeductionMoney)
            )
            fuDataVal.surplusNum = this.roundingFour(
                fuDataVal.shNum - fuDataVal.sumNum
            )
            this.$set(row, 'isProgressEdit', false)
            this.$set(row, 'edit', false)
            this.onCellValidation(row, fuDataVal)
            this.initCellColor()
        },
       async getNewData(){
           this.queryInspectionValuationDetailsAll({
               prjId: this.query.prjId || this.prjId
           })
           this.getServiceReceInspection({
               prjId: this.query.prjId || this.prjId
           })
           const res = await getItAccInfo({
               prjId: this.query.prjId || this.prjId
           })
           if (+res.code === 200) {
               this.isTardeOrAdd =
                   res.data.find((item) => item.itAccId === this.itAccId)
                       ?.type === '新增'
                       ? 1
                       : 2
           }
        },
        // 数据复原 用于校验出错
        resetData(row, fuDataVal) {
            row.currentInspectionNum = this.oldRow.currentInspectionNum
            row.currentInspectionMoney = this.oldRow.currentInspectionMoney
            row.projectProGress = this.oldRow.projectProGress
            row.currentDeductionMoney = this.oldRow.currentDeductionMoney
            fuDataVal.sumNum = this.oldParentRow.sumNum
            fuDataVal.sumMoney = this.oldParentRow.sumMoney
            fuDataVal.surplusNum = this.oldParentRow.surplusNum
            this.getNewData()
        },
        // 新校验针对数量和金额都是负数的
        onCellValidationNewCheck(record, fuDataVal) {
            if(record.spcalTag&&this.isshowPrjDetailInfo){
                console.log(record.currentInspectionNum);
                if(Number(record.currentInspectionNum)===0){
                    this.$message({
                    message: '本期验工数量不能为0!',
                    type: 'warning'
                    })
                  this.resetData(record, fuDataVal)
                  throw ""
                }
                if(Number(record.currentInspectionNum)>0){
                    this.$message({
                    message: '本期验工数量不能大于0!',
                    type: 'warning'
                    })
                  this.resetData(record, fuDataVal)
                   throw ""
                }
                this.saveData(record, fuDataVal)
                throw ""
            }
        },
        // 失去焦点校验
        onCellValidation(record, fuDataVal) {
            const shNum = fuDataVal.shNum
            const shMoney = fuDataVal.shMoney
            const projectProGress = record.projectProGress
            if (
                isNaN(record.currentInspectionNum) ||
                isNaN(record.currentInspectionMoney)
            ) {
                this.$message({
                    message: '非法字符!',
                    type: 'warning'
                })
                this.resetData(record, fuDataVal)
                return
            }
            this.onCellValidationNewCheck(record, fuDataVal)
            if (Number(record.currentInspectionNum) <= 0) {
                this.$message({
                    message: '本期验工数量必须填写正数!',
                    type: 'warning'
                })
               this.resetData(record, fuDataVal)
                return
            }
            if (Number(record.currentTinSpectionNum) > shNum) {
                this.$message({
                    message: '当前预估单的累计验工数量应小于等于商合预占数!',
                    type: 'warning'
                })
                this.resetData(record, fuDataVal)
                return
            }
            if (Number(record.currentInspectionMoney) > shMoney) {
                // 原始的本期验工金额
                this.$message({
                    message: '当前预估单的累计验工金额应小于等于商合预占金额！',
                    type: 'warning'
                })
                this.resetData(record, fuDataVal)
                return
            }
            if (projectProGress > 100 || projectProGress < 0) {
                this.$message({
                    message: '验工计价进度输入数字必须在0-100之间',
                    type: 'warning'
                })
                this.resetData(record, fuDataVal)
                return
            }
            this.saveData(record, fuDataVal)
        },
        async saveDatarepairOne(checkIfValidateRes,serviceCode,currentInspectionNum,shNum,row,fuDataVal){
            if (+checkIfValidateRes.code === 200) {
                if (checkIfValidateRes.data === '0') {
                    let AllspuUnitAcc = '' // 储存获取的精度
                    let yuzhanJingdu = '' // 储存预占数数量精度
                    const obj1 = {
                        materialCode: serviceCode
                    }
                    const jingDuData = await getMaterialInfo(obj1)
                    AllspuUnitAcc = await this.saveDatarepairTwo(jingDuData,AllspuUnitAcc)
                    var shuliang = currentInspectionNum.toString().replace('.', ',')
                    var shuliangArr = shuliang.split(',')

                    var shJingdu = shNum.toString().replace('.', ',') // 商合预占数精度
                    var shJingduArr = shJingdu.split(',')
                    yuzhanJingdu = await this.saveDatarepairThree(shJingduArr,yuzhanJingdu)

                    // var shuliang = currentInspectionNum.toString().replace('.', ',')
                    // var shuliangArr = shuliang.split(',')
                   await this.saveDatarepairFour(shuliangArr,jingDuData,AllspuUnitAcc,yuzhanJingdu,row,fuDataVal)
                }
            }
        },
        async saveDatarepairTwo(jingDuData,AllspuUnitAcc){
            let backAllspuUnitAcc = AllspuUnitAcc
            if (jingDuData.code === '200') {
                if (jingDuData.data.spuUnitAcc === '0') {
                    backAllspuUnitAcc = '整数'
                } else {
                    backAllspuUnitAcc = jingDuData.data.spuUnitAcc + '位小数'
                }
            }
            return backAllspuUnitAcc
        },
        async saveDatarepairThree(shJingduArr,yuzhanJingdu){
            let backyuzhanJingdu = yuzhanJingdu
            if (shJingduArr.length === 1) {
                backyuzhanJingdu = '整数'
            }
            if (shJingduArr.length === 2) {
                backyuzhanJingdu = shuliangArr[1].length + '位小数'
            }
            return backyuzhanJingdu
        },
        async saveDatarepairFour(shuliangArr,jingDuData,AllspuUnitAcc,yuzhanJingdu,row,fuDataVal){
            if (shuliangArr.length === 2 && +shuliangArr[1] > Number(jingDuData.data.spuUnitAcc)) {
                // 有小数时候, 小数精度 大于 预占数精度时候
                this.$message({
                    message:
                        '本期验工数量精度填写不正确，本期验工数量精度为' +
                        AllspuUnitAcc +
                        '，物料精度为' +
                        yuzhanJingdu,
                    type: 'warning'
                })
                this.resetData(row, fuDataVal)
                return Promise.reject()
            } 
        },
        async saveDatarepairFive(currentInspectionMoney,currentInspectionNum,fuDataVal,row){
            if(!(row.spcalTag&&this.isshowPrjDetailInfo)){
                if (currentInspectionMoney < 0 || currentInspectionNum < 0) {
                this.$message({
                    message: '当前为新增验工计价，请填写正数验工计价！',
                    type: 'warning'
                })
                this.resetData(row, fuDataVal)
                return Promise.reject()
            } 
             if (currentInspectionMoney < 0) {
                this.$message({
                    message: '当前为新增验工计价，请填写正数验工计价！',
                    type: 'warning'
                })
                this.resetData(row, fuDataVal)
                return Promise.reject()
            }
            } 
        },
        async saveDatarepairSix(sumNum,shMoney,sumMoney,currentInspectionMoney,row,fuDataVal){
          if(!(row.spcalTag&&this.isshowPrjDetailInfo)){
            if (sumNum < 0) {
                this.$message({
                    message: '当前预估单的累计验工数量应大于等于0！',
                    type: 'warning'
                })
                this.resetData(row, fuDataVal)
                return Promise.reject()
            }
            if (Number(currentInspectionMoney) > Number(shMoney)) {
                this.$message({
                    message: '本期验工金额应小于商合预占金额',
                    type: 'warning'
                })
                this.resetData(row, fuDataVal)
                return Promise.reject()
            }
            if (Number(sumMoney) > Number(shMoney) || Number(sumMoney) < 0) {
                this.$message({
                    message:
                        '当前预估单的累计验工金额应小于等于商合预占金额且大于等于0！',
                    type: 'warning'
                })
                this.resetData(row, fuDataVal)
                return Promise.reject()
            }
            }
        },
        async saveDatarepairSeven(allServiceShNumSum,allServiceTServListAmount,allServiceTServListAdjAmount){
            return allServiceShNumSum < allServiceTServListAmount
                            ? allServiceShNumSum < allServiceTServListAdjAmount
                                ? allServiceShNumSum
                                : allServiceTServListAdjAmount
                            : allServiceTServListAmount <
                                allServiceTServListAdjAmount
                                ? allServiceTServListAmount
                                : allServiceTServListAdjAmount
        },
        async saveDatarepairEight(allServiceShNumSum,allServiceTServListAmount,minSumNum){
            let backminSumNum = minSumNum
            if (allServiceShNumSum > allServiceTServListAmount) {
                // 服务所有订单下商合预占数量的和 大于设计表服务数量
                backminSumNum = allServiceTServListAmount
            } else {
                backminSumNum = allServiceShNumSum
            }
            return backminSumNum
        },
        async saveDatarepairNine(allServiceSumNum,minSumNum ,row,fuDataVal){
            if(!(row.spcalTag&&this.isshowPrjDetailInfo)){
            if (allServiceSumNum > minSumNum) {
                    this.$message({
                        message:
                            '当前服务编码所有预估单累计验工数量应小于等于本服务所有预估单的累计商合预占数或设计清单数量！',
                        type: 'warning'
                    })
                    this.resetData(row, fuDataVal)
                    return Promise.reject()
                }
                if (allServiceSumNum < 0) {
                    this.$message({
                        message: '本服务所有预估单的累计验工数量应大于等于0！',
                        type: 'warning'
                    })
                    this.resetData(row, fuDataVal)
                    return Promise.reject()
                } 
            }
        },
        async saveDatarepairTen(shNum,sumMoney,shMoney,sumNum,projectProgress,row,fuDataVal){
            if ( Number(sumMoney) === Number(shMoney) &&projectProgress !== '100') {
                this.$message({
                    message:
                        '当前预估单累计验工金额等于商合预占金额，需要将项目进度填为100！',
                    type: 'warning'
                })
                this.resetData(row, fuDataVal)
                return Promise.reject()
            }
            if (Number(sumNum) === Number(shNum) && projectProgress !== '100') {
                this.$message({
                    message:
                        '当前预估单累计验工数量等于商合预占数量，需要将项目进度填为100！',
                    type: 'warning'
                })
                this.resetData(row, fuDataVal)
                return Promise.reject()
            }
        },
         async saveDatarepairEleveNew(data){
            const updateInsValITs = await updateInsValITNew(data)
            if (updateInsValITs.code === '200') {
                this.queryInspectionValuationDetailsAll({
                    prjId: this.query.prjId || this.prjId
                })
                this.$message({
                    message: '保存成功',
                    type: 'success'
                })
            } else {
                this.queryInspectionValuationDetailsAll({
                    prjId: this.query.prjId || this.prjId
                })
            }
         },
        async saveDatarepairEleve(data){
            const show =Number(data.currentInspectionNum)<0&&Number(data.currentInspectionMoney)<0
            const showOne = Number(data.sumMoney)===0&&Number(data.sumNum)>0
            if(this.isshowPrjDetailInfo&&show&&showOne){
                this.$confirm(`本次冲销后累计验工计价金额是0，累计验工计价数量也必须为0，请确认！`, '系统提示', {
                                dangerouslyUseHTMLString: true,
                                confirmButtonText: '确认',
                                cancelButtonText: '取消',
                                cancelButtonClass: 'pms-zr-button',
                                confirmButtonClass: 'pms-zr-button-primary',
                                type: 'warning'
                            }).then(async() => {
                                await this.saveDatarepairEleveNew(data)
                            }).catch(() => {
                                this.queryInspectionValuationDetailsAll({
                                    prjId: this.query.prjId || this.prjId
                                })
                            })
                 return
            }
            await this.saveDatarepairEleveNew(data)
        },
        // 失去焦点后保存校验 &&  保存事件
        async saveData(row, fuDataVal) {
            const pId = row.pid
            const vId = row.vid
            const prjId = row.prjId
            const subPrjId = row.subPrjId
            const serviceCode = fuDataVal.serviceCode
            const siteId = fuDataVal.siteId
            const currentInspectionMoney = row.currentInspectionMoney
            const currentInspectionNum = row.currentInspectionNum
            const projectProgress = row.projectProGress
            const shMoney = fuDataVal.shMoney
            const shNum = fuDataVal.shNum
            const sumNum = fuDataVal.sumNum
            const sumMoney = fuDataVal.sumMoney
            const taxrate = fuDataVal.taxrate // 税率
            const onlyBe1Flag = fuDataVal.onlybe1flag
            const purchaseMode = fuDataVal.purchaseMode
            const orderDetailId = fuDataVal.orderDetailId
            const currentDeductionMoney = this.farmatMoney(
                Number(Math.abs(row.currentDeductionMoney))
            )
            var payType = row.payType
            const prjIdNew = this.query.prjId || this.prjId
            const checkIfValidateRes = await checkIfValidatePrecision(prjIdNew)
            
            await this.saveDatarepairOne(checkIfValidateRes,serviceCode,currentInspectionNum,shNum,row,fuDataVal)
            await this.saveDatarepairFive(currentInspectionMoney,currentInspectionNum,fuDataVal,row)
           await this.saveDatarepairSix(sumNum,shMoney,sumMoney,currentInspectionMoney,row,fuDataVal)
            // 保存验工计价通用校验 ↓
            var flag = false
            // var allServiceSumMoney = 0 // 服务所有订单下累计验工金额
            var allServiceSumNum = 0 // 服务所有订单下累计验工数量
            // var allServiceShMoneySum = 0 // 服务所有订单下商合预占金额的和
            var allServiceShNumSum = 0 // 服务所有订单下商合预占数量的和
            // var allServiceTServListEquipSum = 0 // 设计表服务及金额
            var allServiceTServListAmount = 0 // 设计表服务数量
            var allServiceTServListAdjAmount = 0 // 设计变更表服务数量
            // var allServiceTServListAdjEquipSum = 0 // 设计变更表服务及金额
            var allSupplementNum = 0 // 在建工程损失补采数量
            var minSumNum = 0
            const obj = {
                serviceCode: serviceCode,
                subPrjId: subPrjId,
                prjId: prjId,
                type: '0'
            }
            const gCheckData = await getCheckInsVaData(obj)
            if (gCheckData.code === '200') {
                // allServiceSumMoney = this.farmatMoney(Number(gCheckData.data.currentInspectionSum.CURRENT_INSPECTION_MONEY_SUM) + Number(currentInspectionMoney))
                allServiceSumNum = this.farmatNum(
                    Number(
                        gCheckData.data.currentInspectionSum
                            .CURRENT_INSPECTION_NUM_SUM
                    ) + Number(currentInspectionNum)
                ) // 所有订单累计数量+当前所填本期验工数量
                //  allServiceShMoneySum = gCheckData.data.shSum.SH_MONEY_SUM
                allServiceShNumSum = gCheckData.data.shSum.SH_NUM_SUM
                // allServiceTServListEquipSum = gCheckData.data.serListSum[0].SJ_MONEY
                allServiceTServListAmount =gCheckData.data.serListSum.SJ_AMOUNT
                // if (allServiceTServListAmount === null) {
                //     console.log('服务设计表中无该条服务数据')
                // }
                if (gCheckData.data.serListAdjSum.SJ_ADJ_AMOUNT ||gCheckData.data.serListAdjSum.SJ_ADJ_MONEY) {
                    // 设计变更表中有数据已发生设计变更  在商合、设计、设计变更 金额中取最小值
                    // 设计表服务预算合价+在建工程损失金额
                    // allServiceTServListAdjEquipSum = gCheckData.data.serListAdjSum.SJ_ADJ_MONEY
                    allServiceTServListAdjAmount =
                        gCheckData.data.serListAdjSum.SJ_ADJ_AMOUNT
                    // if (allServiceTServListAdjAmount === null) {
                    //     console.log('服务设计变更表中无该条服务数据')
                    //     //  console.log(allServiceSumMoney, allServiceShMoneySum, allServiceTServListEquipSum, allServiceTServListAdjEquipSum)
                    // }
                    // 设计表服务建设数量+在建工程损失数量
                    allServiceTServListAdjAmount =
                        gCheckData.data.serListAdjSum.SJ_ADJ_AMOUNT +
                        allSupplementNum
                    // 商合、设计+补采、设计变更+补采取最小值
                    minSumNum =await this.saveDatarepairSeven(allServiceShNumSum,allServiceTServListAmount,allServiceTServListAdjAmount)
                        
                } else {
                    minSumNum = await this.saveDatarepairEight(allServiceShNumSum,allServiceTServListAmount,minSumNum)
                }
                await this.saveDatarepairNine(allServiceSumNum,minSumNum ,row,fuDataVal)
            }
            // if (flag) {
            //     return
            // }

            await this.saveDatarepairTen(shNum,sumMoney,shMoney,sumNum,projectProgress,row,fuDataVal)
            let inspectionTax =
                (this.farmatMoney(currentInspectionMoney) -
                    this.farmatMoney(currentDeductionMoney)) *
                Number(taxrate) // 验工计价税额 = 本期验工金额*税率
            inspectionTax = this.farmatMoney(inspectionTax)
            const inspectionTaxAmount = this.farmatMoney(
                Number(currentInspectionMoney) + Number(inspectionTax) - currentDeductionMoney
            ) // 含税验工计价总金额 = 本期验工金额 + 验工计价税额
            const data = {
                pId: pId,
                prjId: prjId,
                subPrjId: subPrjId,
                onlyBe1Flag: onlyBe1Flag,
                siteId: siteId,
                serviceCode: serviceCode,
                currentInspectionNum: currentInspectionNum,
                currentInspectionMoney: currentInspectionMoney,
                currentDeductionMoney: -currentDeductionMoney,
                sumMoney: sumMoney,
                sumNum: sumNum,
                projectProgress: projectProgress,
                inspectionTax: inspectionTax,
                inspectionTaxAmount: inspectionTaxAmount,
                orderDetailId: orderDetailId,
                purchaseMode: purchaseMode,
                payType: payType,
                flag: '2',
                vid: vId
            }
            await this.saveDatarepairEleve(data)
        },
        updateCellColor(row, show) {
            this.tableData.forEach(item => {
                if (item?.vid !== row?.vid && show) {
                    this.$set(item, 'isProgressEdit', false)
                    this.$set(item, 'edit', false)
                    this.$set(item, 'isCurrentDeductionMoney', false)
                }
            })
        },
        // 开启编辑状态
        handleEdit(row, type,show=true) {
            if (!this.isEdit) {
                return false
            }
            this.updateCellColor(row,show)
            this.oldCspectionNum = row.currentInspectionNum
            this.oldCspectionMoney = row.currentInspectionMoney
            this.oldRow = JSON.parse(JSON.stringify(row))
            if (type === 'projectProGress') {
                this.flageColor.projectProGressColor = show
                this.$set(row, 'isProgressEdit', true)
            } else if (type === 'currentInspectionNum') {
                this.flageColor.currentInspectionNumColor = show
                this.$set(row, 'edit', true)
            } else if (type === 'currentDeductionMoney') {
                this.flageColor.currentDeductionMoneyColor = show
                this.$set(row, 'isCurrentDeductionMoney', true)
            } else {
                console.log(111);
            }
        },
        payType(row) {
            switch (row.paymentType) {
                case 'FIRST':
                    return '首付款（含安全生产费）'
                case 'PROGRESSING':
                    return '进度款'
                case 'LOSS':
                    return '损失款'
                default:
                    break
            }
        },
        async queryInspectionValuationDetailsAll(params) {
            const { code, data } = await queryInsValDetailsTao(params)
            if (+code === 200) {
                this.tableData = data.map((_item)=>{
                    return {
                        ..._item,
                        spcalTag:(+_item.currentInspectionNum)<0&&(+_item.currentInspectionMoney)<0
                    }
                })
                this.$emit('InspectionValuationDetails', this.tableData)
                for (const item of this.tableData) {
                    if (item.pid === '0') {
                        this.fatherNodeArr.push(item) // 获取所有父节点
                    }
                }
            }
        },
        async getServiceReceInspection(params) {
            const { code, data } = await getServiceReceInspection(params)
            if (+code === 200 && data.length > 0) {
                data.map((v) => {
                    this.coding.push(v)
                })
                this.coding = this.coding.join(',')
            } else {
                this.coding = '无'
            }
        },
        // 获取关联父子数据得orderState
        getParentNodeOrderState(e) {
            let parentVal = ''
            this.fatherNodeArr.map((fuVal) => {
                if (fuVal.vid === e.pid) {
                    parentVal = fuVal.orderState
                }
            })
            return parentVal
        },
        // 获取所有相关预估单下待冲销数据
        getTradeChildren(parentNode) {
         return this.tableData.filter(item => {
                return parentNode.vid === item.pid
            })
        },
        // 2024-10-09 阻断问题if过多解决方案
        optimizeNewAddone(row) {
            if (row.shNum - row.sumNum === 0) {
                this.$message({
                    message:
                        '当前累计验工计价数量等于商合预占数量,不支持新增操作!',
                    type: 'warning'
                })
                return true
            }
            if (row.shMoney - row.sumMoney === 0) {
                this.$message({
                    message:
                        '当前累计验工计价金额等于商合预金额,不支持新增操作!',
                    type: 'warning'
                })
                return true
            }
            return false
        },
        async optimizeNewAddTwo(row) {
            const { code, data } = await getHaveInspection({
                itAccId: this.itAccId,
                vId: row.vid
            })
            if (+code === 200 && +data) {
                return true
            } else {
                return false
            }
        },
        optimizeNewAddThree(fuZiArr, index) {
            return fuZiArr[index].projectProGress === '100' &&
                    fuZiArr[index].payType === 'PROGRESSING'
        },
       async optimizeNewAddFour(dataParams) {
        const updateInsValITRes = await updateInsValITNew(dataParams)
            if (updateInsValITRes.code === '200') {
                if (updateInsValITRes.message === '操作成功') {
                    this.queryInspectionValuationDetailsAll({
                        prjId: this.query.prjId || this.prjId
                    })
                    this.$message({
                        message: '新增成功',
                        type: 'success'
                    })
                } else {
                    this.$message({
                        message: '新增失败',
                        type: 'error'
                    })
                }
            }
        },
        // 数组插入
        async add(row) {
            const params = {
                pId: row.vid,
                prjId: row.prjId,
                subPrjId: row.subPrjId,
                serviceCode: row.serviceCode,
                siteId: row.siteId,
                currentInspectionMoney: this.farmatMoney(
                    row.shMoney - row.sumMoney
                ),
                currentInspectionNum: row.surplusNum,
                projectProgress: '100',
                sumNum: row.shNum, // 新增累计数量直接等于商合预占数
                sumMoney: row.shMoney, // 新增累计金额直接等于商合预金额
                taxrate: row.taxrate, // 税率
                onlyBe1Flag: row.onlybe1flag,
                purchaseMode: row.purchaseMode,
                orderDetailId: row.orderDetailId
            }
            // 2024-10-09 阻断问题if过多解决方案
            if (this.optimizeNewAddone(row)) {
                return
            }
            let flag = false
            flag = await this.optimizeNewAddTwo(row)
            if (flag) {
                return this.$message.warning(
                    '当前验收阶段已存在未推送商合的验工计价信息，请删掉重新做验工计价！'
                )
            }
            const fuZiArr = []
            this.tableData.map((v) => {
                if (v.pid === this.fatherNodeArr[0].vid) {
                    fuZiArr.push(v)
                }
            })
            for (let index = 0; index < fuZiArr.length; index++) {
                if (this.optimizeNewAddThree(fuZiArr, index)) {
                    this.sign = true
                }
            }
            let inspectionTax =
                Number(params.currentInspectionMoney) * Number(params.taxrate) // 验工计价税额 = 本期验工金额*税率
            inspectionTax = this.farmatMoney(inspectionTax)
            const inspectionTaxAmount = this.farmatMoney(
                Number(params.currentInspectionMoney) + Number(inspectionTax)
            )
            const dataParams = {
                ...params,
                inspectionTax: inspectionTax,
                inspectionTaxAmount: inspectionTaxAmount,
                payType: 'PROGRESSING',
                sign: this.sign,
                flag: '1',
                itAccId: this.itAccId
            }
            this.optimizeNewAddFour(dataParams)
        },
        async traderepairOne(fuDataVal){
            if (fuDataVal.sumNum < 0 || fuDataVal.sumMoney < 0) {
                    this.$message({
                        message: '本服务所有预估单的累计验工数量应大于等于0！',
                        type: 'warning'
                    })
                    return Promise.reject()

                }
        },
        async traderepairTwo(data){
            const updateInsValIT_s = await updateInsValITNew(data)
            if (updateInsValIT_s.code === '200') {
                if (updateInsValIT_s.message === '操作成功') {
                    this.queryInspectionValuationDetailsAll({
                        prjId: this.query.prjId || this.prjId
                    })
                    this.$message({
                        message: '冲销成功',
                        type: 'success'
                    })
                } else {
                    this.$message({
                        message: '冲销失败',
                        type: 'error'
                    })
                }
            }
        },
        // 冲销
        async trade(rowUnion) {
            let fuDataVal = ''
            this.fatherNodeArr.map((fuVal) => {
                if (fuVal.vid === rowUnion.pid) {
                    fuDataVal = fuVal
                }
            })
            this.$confirm('本次冲销为全量冲销，是否继续', '冲销提醒', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                customClass: 'pms-confirm',
                type: 'warning'
            }).then(async () => {
                const tradeData = this.getTradeChildren(fuDataVal)
                console.log(tradeData)
                const row = JSON.parse(JSON.stringify(rowUnion))
                row.currentInspectionNum = 0
                let currentInspectionMoneyTotal = 0
                for (const item of tradeData) {
                    if (Math.sign(row.currentInspectionMoney) === 1) {
                        currentInspectionMoneyTotal += (Number(item.currentInspectionMoney) - Number(Math.abs(item.currentDeductionMoney)))
                        row.currentInspectionNum += Number(item.currentInspectionNum)
                    }
                }
                row.currentInspectionMoney = currentInspectionMoneyTotal
                const pId = row.pid
                const vId = row.vid
                const prjId = row.prjId
                const subPrjId = row.subPrjId
                const serviceCode = fuDataVal.serviceCode
                const siteId = fuDataVal.siteId
                const currentInspectionMoney = -(row.currentInspectionMoney)
                const currentInspectionNum = -Number(row.currentInspectionNum)
                const projectProgress = row.projectProGress
                const sumNum = this.farmatNum(
                    Number(fuDataVal.sumNum) - Number(row.currentInspectionNum)
                )
                const sumMoney = this.farmatMoney(
                    Number(fuDataVal.sumMoney) - Number(row.currentInspectionMoney)
                ) // 冲销累计金额直接等于累计金额 -当前金额
                const taxrate = fuDataVal.taxrate // 税率
                const onlyBe1Flag = fuDataVal.onlybe1flag
                const purchaseMode = fuDataVal.purchaseMode
                const orderDetailId = fuDataVal.orderDetailId
                const fuZiArr = []
                this.tableData.map((v) => {
                    if (v.pid === this.fatherNodeArr[0].vid) {
                        fuZiArr.push(v)
                    }
                })
                for (let i = 0; i < fuZiArr.length; i++) {
                    // 进度100 且 付款类型为首付款的时候 sign =true
                    if (
                        fuZiArr[i].projectProGress === '100' &&
                        fuZiArr[i].payType === 'PROGRESSING'
                    ) {
                        this.sign = true
                    }
                }
                var inspectionTax =
                    Number(currentInspectionMoney) * Number(taxrate) // 验工计价税额 = 本期验工金额*税率
                inspectionTax = this.farmatMoney(inspectionTax)
                const inspectionTaxAmount = this.farmatMoney(
                    Number(currentInspectionMoney) + Number(inspectionTax)
                ) // 含税验工计价总金额 = 本期验工金额 + 验工计价税额
                var data = {
                    pId: pId,
                    prjId: prjId,
                    subPrjId: subPrjId,
                    onlyBe1Flag: onlyBe1Flag,
                    siteId: siteId,
                    serviceCode: serviceCode,
                    currentInspectionNum: currentInspectionNum,
                    currentInspectionMoney: currentInspectionMoney,
                    sumMoney: sumMoney,
                    sumNum: sumNum,
                    projectProgress: projectProgress,
                    inspectionTax: inspectionTax,
                    inspectionTaxAmount: inspectionTaxAmount,
                    orderDetailId: orderDetailId,
                    purchaseMode: purchaseMode,
                    payType: row.paymentType,
                    flag: '1',
                    ifShowDest: 2,
                    strVid: vId,
                    itAccId: this.itAccId
                }

                await this.traderepairOne(fuDataVal)
                await this.traderepairTwo(data)
            })
        },
        handleDelete(row) {
                 this.$confirm(CHECK_DELETE_TIPS, '删除提醒', {
                    cancelButtonText: '取消',
                    confirmButtonText: '确定',
                    customClass: 'pms-confirm',
                     cancelButtonClass: 'pms-zr-button',
                     confirmButtonClass: 'pms-zr-button-primary',
                    type: 'warning'
                }).then(() => {
                    this.deleteData(row)
                })
        },
        sloveDelete(diffNum,diffMoney,row){
            if(+row.ifSingleZL!==1){
                if (diffNum < 0) {
                this.$message({
                    message: '本订单的累计验工数量应大于等于0！',
                    type: 'warning'
                })
                throw ''
            }
            if(!(this.prjDetail.isNewbusiness==='1'&&['25','29'].includes(this.prjDetail.buildModes))){
                if (diffMoney < 0) {
                this.$message({
                    message: '本订单的累计验工金额应大于等于0！',
                    type: 'warning'
                })
                throw ''
                    }
                }
            }
        },
        deleteData(row) {
            let parentNode = ''
            this.fatherNodeArr.map((item) => {
                if (item.vid === row.pid) {
                    parentNode = item
                }
            })
            const currentInspectionNum = row.currentInspectionNum
            const currentInspectionMoney = row.currentInspectionMoney
            const sumNum = parentNode.sumNum // 该订单累计验工数量
            const sumMoney = parentNode.sumMoney // 该订单累计验工金额
            const diffNum = Number(sumNum) - Number(currentInspectionNum)
            const diffMoney = Number(sumMoney) - Number(currentInspectionMoney)
            this.sloveDelete(diffNum,diffMoney,row)
            // if (diffNum < 0) {
            //     // if (parentNode.onlybe1flag === 'N' && diffNum < 0) {
            //     this.$message({
            //         message: '本订单的累计验工数量应大于等于0！',
            //         type: 'warning'
            //     })
            //     return
            // }
            // if (diffMoney < 0) {
            //     // if(parentNode.ONLYBE1FLAG=="Y"&&diffMoney<0){
            //     this.$message({
            //         message: '本订单的累计验工金额应大于等于0！',
            //         type: 'warning'
            //     })
            //     return
            // }
            this.$confirm('确认删除该明细？', '删除提醒', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                type: 'warning'
            }).then(async() => {
                // treegrid.loading("删除中，请稍后......")
                var ifShowDest = ''
                var strVid = ''
                if (row.strVid) {
                    ifShowDest = 1
                    strVid = row.strVid
                } else {
                    ifShowDest = 2
                }
                const onlyBe1Flag = parentNode.onlybe1flag
                const pId = row.pid
                const vId = row.vid
                const currentInspectionNums = row.currentInspectionNum
                const currentInspectionMoneys = row.currentInspectionMoney
                const serviceCode = parentNode.serviceCode
                const prjId = parentNode.prjId
                const subPrjId = parentNode.subPrjId
                const data = {
                    onlyBe1Flag: onlyBe1Flag,
                    currentInspectionNum: currentInspectionNums,
                    currentInspectionMoney: currentInspectionMoneys,
                    serviceCode: serviceCode,
                    prjId: prjId,
                    subPrjId: subPrjId,
                    pId: pId,
                    vId: vId,
                    flag: '3',
                    ifShowDest: ifShowDest,
                    strVid: strVid
                }
                const updateInsValITRes = await updateInsValITNew(data)
                if (updateInsValITRes.code === '200') {
                    this.queryInspectionValuationDetailsAll({
                        prjId: this.query.prjId || this.prjId
                    })
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    })
                } else {
                    this.$message({
                        message: updateInsValITRes.message,
                        type: 'warning'
                    })
                }
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.text-align-left {
    line-height: 25px;
    text-align: left;
}
::v-deep .el-table__fixed-right {
    height: 100% !important;
}

#messBox {
    word-break: break-all;
}
.header-tooltip {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: block;
  cursor: pointer;
}
.custom-required .el-form-item__label::before {
  content: '*';
  color: #ff4949;
  margin-right: 4px;
}
</style>
